package com.dwxt.cdms.controller.wx;

import com.dwxt.cdms.exception.AesException;
import com.dwxt.cdms.service.YouthHopeService;
import com.dwxt.cdms.service.wx.BindService;
import com.dwxt.cdms.util.XMLUtil;
import com.dwxt.cdms.util.wx.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;

@Slf4j
@RequestMapping("/cdms/authentication")
@RestController
public class AuthenticationController {

    @Autowired
    private BindService bindService;

    /**
     * 微信消息解析
     */
    @GetMapping("/wx")
    public void  getCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // get方法主要处理公众号接入部分
        String signature=request.getParameter("signature");
        String timestamp=request.getParameter("timestamp");
        String nonce=request.getParameter("nonce");
        String echostr=request.getParameter("echostr");
        PrintWriter pWriter=response.getWriter();
        if(CheckUtil.checkSignature(signature, timestamp, nonce)) {
            pWriter.print(echostr);
            pWriter.close();
        }
    }

    /**
     * 微信消息解析
     */
    @PostMapping("/wx")
    public void  getMsg(HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam(name = "timestamp",required = false) String timestamp,
                        @RequestParam(name = "nonce", required = false) String nonce,
                        @RequestParam(name = "signature", required = false) String signature,
                        @RequestParam(name = "msg_signature", required = false) String msg_signature)
            throws IOException {
        //接受微信服务器发送过来的XML形式的消息
        InputStream in=request.getInputStream();
        BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
        String sReqData="";
        String itemStr="";//作为输出字符串的临时串，用于判断是否读取完毕
        while((itemStr=reader.readLine())!=null){
            sReqData+=itemStr;
        }
        in.close();
        reader.close();
        System.out.println("收到消息："+sReqData);
        //防止中文乱码
        response.setCharacterEncoding("UTF-8");
        Document document = XMLUtil.readString2XML(sReqData);
        Element root = document.getRootElement();
        //解密
        if (XMLUtil.readNode(root,"Encrypt")!=null){
            try {
                sReqData=CheckUtil.decryptMsg(sReqData,timestamp,nonce,signature);
            } catch (AesException e) {
                log.error("解码失败");
            } catch (ParserConfigurationException e) {
                log.error("类型转换失败");
            } catch (SAXException e) {
                e.printStackTrace();
            }
        }
        //接受微信消息并执行业务
        bindService.replyMessage(sReqData,response);
    }
}